package com.norns.torque.socket

import android.widget.Toast
import com.norns.torque.entrty.WifiDevice
import com.norns.torque.listener.ConnectedListener
import com.norns.torque.listener.MessageListener
import com.norns.torque.network.NetworkListenerHelper
import com.norns.torque.network.NetworkStatus
import com.norns.torque.utils.AppConstant
import com.norns.torque.utils.AppContext
import com.norns.torque.utils.DataConversion
import timber.log.Timber
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetSocketAddress
import java.net.Socket

object ClientSocket {
    private var mClientSocket: Socket? = null
    private var mInputStream: InputStream? = null
    private var mOutputStream: OutputStream? = null
    var isConnected = false

    private var mMessageListenerList: ArrayList<MessageListener> = ArrayList()
    private var mConnectedListener: ArrayList<ConnectedListener> = ArrayList()

    //连接状态监听
    fun addConnectionListener(listener:ConnectedListener){
        mConnectedListener.add(listener)
    }

    //消息监听
    fun addMessagesListener(listener:MessageListener){
        mMessageListenerList.add(listener)
    }

    fun removeConnectionListener(listener:ConnectedListener){
        if (mConnectedListener.isNotEmpty()) {
            mConnectedListener.remove(listener)
        }
    }
    fun removeMessagesListener(listener:MessageListener){
        if (mMessageListenerList.isNotEmpty()) {
            mMessageListenerList.remove(listener)
        }
    }
    private var networkListenerHelper : NetworkListenerHelper.NetworkConnectedListener?=null

    fun registerNetwork(){
        networkListenerHelper= object : NetworkListenerHelper.NetworkConnectedListener{
            override fun onNetworkConnected(isConnected: Boolean, networkStatus: NetworkStatus) {
                if (!isConnected || networkStatus!= NetworkStatus.WIFI){
                    Toast.makeText(AppContext.context, "wifi已断开", Toast.LENGTH_SHORT).show()
                    setContentState(AppConstant.connectionField)
                    close()
                }
            }
        }
        NetworkListenerHelper.addListener(networkListenerHelper!!)
    }

    fun unregisterNetwork(){
        networkListenerHelper?.let {
            NetworkListenerHelper.removeListener(networkListenerHelper)
            networkListenerHelper=null
        }
    }

    fun contentToDevice(device: WifiDevice){
        try {
            if (null != mClientSocket) {
                mClientSocket!!.close()
                mClientSocket = null
            }
            // 创建 Socket 并连接到 ESP32
            mClientSocket = Socket()
            mClientSocket!!.connect(InetSocketAddress(device.address, device.port), 3000)// 设置超时时间为5秒
            mInputStream = mClientSocket!!.getInputStream()
            mOutputStream = mClientSocket!!.getOutputStream()
            isConnected = true
            setContentState(AppConstant.connectionSuccess)
            readMsgInternal()
        } catch (e: IOException) {
            e.printStackTrace()
            setContentState(AppConstant.connectionField)
            isConnected = false
            return
        }
    }
    fun setContentState(state:Int){
        mConnectedListener.forEach { listener->
            listener.onConnected(state)
        }
    }

    private fun readMsgInternal() {
        while (isConnected) {
            val buffer = ByteArray(1024)
            //循环执行read，用来接收数据。
            //数据存在buffer中，count为读取到的数据长度。
            try {
                val count = mInputStream!!.read(buffer)
                val hexStr = DataConversion.encodeHexString(buffer)
                //val str = String(buffer, charset("UTF-8"))
                //_messages.postValue(hexStr)
                Timber.d("接收到设备返回的数据: $hexStr")
                if (mMessageListenerList.isNotEmpty()){
                    mMessageListenerList.last().onMessage(hexStr)
                }
            } catch (e: IOException) {
                e.printStackTrace()
                isConnected = false
                setContentState(AppConstant.connectionField)
            }
        }
    }

    fun writeMsgInternal(messageBytes: ByteArray) {
        if (messageBytes.isEmpty() || mOutputStream == null) return
        try {   //发送
            mOutputStream!!.write(messageBytes)
            mOutputStream!!.flush()
        } catch (e: Exception) {
            e.printStackTrace()
            isConnected = false
            setContentState(AppConstant.connectionField)
        }
    }

    fun close() {
        unregisterNetwork()
        isConnected = false
        try {
            if (mOutputStream != null) {
                mOutputStream!!.close()
                mOutputStream = null
            }
            if (mInputStream != null) {
                mInputStream!!.close()
                mInputStream = null
            }
            if (mClientSocket != null) {
                mClientSocket!!.close()
                mClientSocket = null
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}

